//package com.yuantu.judiciary.aop;
//
//import com.yuantu.judiciary.dao.*;
//import com.yuantu.judiciary.model.domain.*;
//import com.yuantu.judiciary.model.enums.*;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.aspectj.lang.ProceedingJoinPoint;;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Propagation;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.persistence.EntityManager;
//import javax.persistence.PersistenceContext;
//import java.sql.*;
//import java.util.List;
//
///**
// * @description：
// * @author: zy
// * @time: 2024-07-24 16:16
// **/
//@Aspect
//@Component
//@RequiredArgsConstructor
//@Slf4j
//public class SaveAspect {
//    @PersistenceContext
//    private EntityManager entityManager;
//
//    @Autowired
//    private DatabaseConfig databaseConfig;
//
//    private final IVipOrderDao vipOrderDao;
//    private final IAccountDao accountDao;
//    private final IMembershipRankDao membershipRankDao;
//    private final IDiscountCodeDao discountCodeDao;
//    private final IInviteRecordDao inviteRecordDao;
//    private final IInviteCodeDao inviteCodeDao;
//    private final IQueryRecordDao queryRecordDao;
//    @Pointcut("execution(* org.springframework.data.repository.CrudRepository.save(..))")
//    public void repositorySave() {}
//
//    @Around("repositorySave()")
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public Object aroundSave(ProceedingJoinPoint joinPoint) throws Throwable {
//        Object[] args = joinPoint.getArgs();
//        VipOrderDO target = null;
//        if (args.length > 0 && args[0] instanceof VipOrderDO) {
//            VipOrderDO newOrder = (VipOrderDO) args[0];
//            if (newOrder.getId() != null) {
//                //VipOrderDO oldOrder = getOldAuthorizedResult(newOrder.getId());
//                VipOrderDO oldOrder = new VipOrderDO();
//                BeanUtils.copyProperties(newOrder, oldOrder);
//
//                oldOrder.setPayState(getOldAuthorizedResult(newOrder.getId()).getPayState());
//                boolean orderPayStateChanged = oldOrder.getPayState() == null || !oldOrder.getPayState().equals(PayState.SUCCESS);
//                System.out.println(orderPayStateChanged);
//                if (newOrder.getPayState().equals(PayState.SUCCESS) &&
//                        orderPayStateChanged) {
//                    //prepay_id不为空说明是微信端的订单
//                    if (StringUtils.isNotEmpty(newOrder.getPrepayId())) {
//                        target = oldOrder;
//                    }
//                }
//            }
//        }
//        if (args.length > 0 && args[0] instanceof QueryRecordDO) {
//            QueryRecordDO newQueryRecord = (QueryRecordDO) args[0];
//            QueryRecordDO oldQueryRecord = new QueryRecordDO();
//            if (newQueryRecord.getId() != null) {
//                BeanUtils.copyProperties(newQueryRecord, oldQueryRecord);
//
//            }
//            boolean queryRecordAuthorizedResultChanged = oldQueryRecord.getAuthorizedResult() != null && !oldQueryRecord.getAuthorizedResult().equals(AuthResultType.AUTHORIZED);
//            if(newQueryRecord.getAuthorizedResult().equals(AuthResultType.AUTHORIZED)
//                    &&queryRecordAuthorizedResultChanged){
//                if(newQueryRecord.getOrigin().equals(EndpointType.ALIPAY_APPLET)){
//                    target = vipOrderDao.findOrderByTradeNoAndDeletedFalse(newQueryRecord.getTradeNo());
//                }
//            }
//        }
//        if (target != null){
////            Integer addScore = null;
////            AccountDO accountDO = null;
////            //首先判断该订单是否是推荐码,如果是推荐码的订单，积分归于推荐码所属的账号，且推荐码有自己的积分比例
////            if(target.getDiscountCodeId() != null){
////                DiscountCodeDO  discountCodeDO = discountCodeDao.findDiscountCodeByIdAndDeletedFalse(target.getDiscountCodeId());
////                if(discountCodeDO.getAccountInfo() != null){
////                    addScore = discountCodeDO.getPointScale();
////                    accountDO = accountDao.findByIdAndDeletedFalse(Long.parseLong(discountCodeDO.getAccountInfo()));
////                }
////            }else{
////                AccountDO accountPay = accountDao.findByIdAndDeletedFalse(target.getCreatorId());
////                List<InviteRecordDO> inviteRecordDO = inviteRecordDao.findRecordByCreatorIdAndTypeAndDeletedFalse(accountPay.getId(), InviteCodeType.INVITE);
////                if(inviteRecordDO.size() > 0){
////                    accountDO = accountDao.findByIdAndDeletedFalse(
////                            inviteCodeDao.findCodeByInviteCodeAndDeletedFalse(inviteRecordDO.get(0).getInviteCode()).getOperatorId()
////                    );
////                    MembershipRankDO membershipRankDO = membershipRankDao.findByIdAndDeletedFalse(accountDO.getMembershipRankId());
////                    addScore = membershipRankDO.getScore();
////                }
////            }
////            //再判断是否订单所属账号是否是被邀请的，如果是被邀请的，积分归于邀请账户，积分比例根据邀请账户会员等级来计算
////            //推荐码和邀请码产生的积分都算作积分总分，都可以用来提升会员等级
////            if(accountDO !=null && addScore !=null){
////                target.setHistoryScore(addScore);
////                updateVipOrder(target);
////                Integer totalHistoryScore = accountDO.getHistoryScore() + addScore;
////                MembershipRankDO rankOption = membershipRankDao.findMembershipRankDOByValue(totalHistoryScore);
////                accountDO.setMembershipRankId(rankOption.getId());
////                accountDO.setHistoryScore(totalHistoryScore);
////                accountDao.save(accountDO);
////            }
//        }
//        return joinPoint.proceed();
//    }
//
//    private VipOrderDO getOldAuthorizedResult(Long id) throws ClassNotFoundException, SQLException {
//        Class.forName(databaseConfig.getJdbcDriver());
//
//        // 建立连接
//        Connection connection = DriverManager.getConnection(
//                databaseConfig.getJdbcUrl(),
//                databaseConfig.getJdbcUsername(),
//                databaseConfig.getJdbcPassword());
//        System.out.println("数据库地址===========" + databaseConfig.getJdbcUrl());
//        // 创建 SQL 查询
//        String sql = "SELECT * FROM vip_order where id = " + id; // 替换为实际的表名
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//
//        // 执行查询
//        ResultSet resultSet = preparedStatement.executeQuery();
//        VipOrderDO vipOrderDO = new VipOrderDO();
//        if(resultSet.next()){
//            vipOrderDO.setId(resultSet.getLong("id"));
//            vipOrderDO.setPayState(PayState.valueOf(resultSet.getString("pay_state")));
//        }
//        resultSet.close();
//        preparedStatement.close();
//        connection.close();
//        return  vipOrderDO;
//    }
//
//
//    private QueryRecordDO getOld(Long id) throws ClassNotFoundException, SQLException {
//        Class.forName(databaseConfig.getJdbcDriver());
//
//        // 建立连接
//        Connection connection = DriverManager.getConnection(
//                databaseConfig.getJdbcUrl(),
//                databaseConfig.getJdbcUsername(),
//                databaseConfig.getJdbcPassword());
//        System.out.println("数据库地址===========" + databaseConfig.getJdbcUrl());
//        // 创建 SQL 查询
//        String sql = "SELECT * FROM vip_order where id = " + id; // 替换为实际的表名
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//
//        // 执行查询
//        ResultSet resultSet = preparedStatement.executeQuery();
//        VipOrderDO vipOrderDO = new VipOrderDO();
//        if(resultSet.next()){
//            vipOrderDO.setId(resultSet.getLong("id"));
//            vipOrderDO.setPayState(PayState.valueOf(resultSet.getString("pay_state")));
//        }
//        resultSet.close();
//        preparedStatement.close();
//        connection.close();
//        return  null;
//    }
//
//
//    private void updateVipOrder(VipOrderDO vipOrderDO) throws ClassNotFoundException, SQLException {
//        Class.forName(databaseConfig.getJdbcDriver());
//
//        Connection connection = null;
//        PreparedStatement preparedStatement = null;
//        // 建立连接
//        connection = DriverManager.getConnection(
//                databaseConfig.getJdbcUrl(),
//                databaseConfig.getJdbcUsername(),
//                databaseConfig.getJdbcPassword());
//
//        // 创建 SQL 查询
//        String sql = "UPDATE vip_order SET history_score = ? WHERE id = ?";
//        preparedStatement = connection.prepareStatement(sql);
//        preparedStatement.setDouble(1, vipOrderDO.getHistoryScore()); // 假设 history_score 是 double 类型
//        preparedStatement.setLong(2, vipOrderDO.getId()); // 假设 id 是 long 类型
//
//        // 执行更新
//        int rowsAffected = preparedStatement.executeUpdate();
//        System.out.println("Rows affected: " + rowsAffected);
//        preparedStatement.close();
//        connection.close();
//    }
//
//
//
//}
